from flask import Blueprint, render_template, send_file, jsonify
import os
from ..config import cfg

download_bp = Blueprint('download_bp', __name__, url_prefix='/download')


@download_bp.route('/', defaults={'path': ''})
@download_bp.route('/<path:path>')
def show_files(path):
    p = os.path.join(cfg.files_dir, path)
    if os.path.isdir(p):
        files = list_files(p)
        return jsonify({'files': files})
    elif os.path.isfile(p):
        return send_file(str(p))
    else:
        return jsonify({'error': 'Not Found'}), 404


def list_files(directory):
    files = []
    # 遍历指定目录下的所有文件和子目录
    for file in os.listdir(directory):
        files.append({'name': file,
                      'path': os.path.join('', str(os.path.relpath(directory, cfg.files_dir)), file)})
    return files
